package com.lzc.camera.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzc.camera.common.CommonResult;
import com.lzc.camera.entity.Config;
import com.lzc.camera.service.AsynsJob;
import com.lzc.camera.service.ConfigService;
import com.lzc.camera.service.LogService;
import com.lzc.camera.utils.DateUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * @Author: lzc
 * @Date: 2022/11/20 23:30
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/camera")
public class CameraController {

    @Autowired
    private AsynsJob asynsJob;
    @Autowired
    private ConfigService configService;
    @Autowired
    private LogService logService;

    @ApiOperation(value = "异步获取图片")
    @RequestMapping("getimage/{pointKey}")
    @ResponseBody
    public CommonResult getImage(@PathVariable String pointKey) {
        /**
         * 通过异步方式获取图片，
         * 1、接口调用返回文件名 摄像头IP地址+时间到毫秒
         * 2、获取图片存放相应路径
         * 3、记录日志保存相关日志信息
         */
        QueryWrapper<Config> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("point_key", pointKey);
        Config config = configService.getOne(queryWrapper);
        if (config == null) {
            return CommonResult.failed("pointKey不存在请验证！");
        }
        String fileName = config.getPointKey() + "-" + config.getIpAddress() + "-" + DateUtils.getDateTime();
        asynsJob.getImage(config.getIpAddress(), fileName, config);

        return CommonResult.success(fileName);
    }

    @ApiOperation(value = "删除180天之前的数据")
    @RequestMapping("delete")
    @ResponseBody
    @Scheduled(cron = "0 0 0 * * ?")
    public CommonResult delete(){
        int delete = logService.delete();
        asynsJob.deleteFile();
        return CommonResult.success(delete);
    }


}
